﻿using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace TFSBugTracking
{
    /// <summary>
    /// class keeping mapping info between one user account and another one to impersonate to in tfs
    /// </summary>
    public class TfsImpersonationMap
    {
        /// <summary>
        /// name (or substring of name) to be translated into different account
        /// Use * char as wild char ("*\zjdau" instead of "cznet\zjdau")
        /// </summary>
        public string SourceUserName { get; set; }

        /// <summary>
        /// The target user name (known to tfs) to impersonate to when filing the bug
        /// </summary>
        public string TargetUserName { get; set; }

        /// <summary>
        /// The password of the impersonating (target) user 
        /// </summary>
        public string TargetPassword { get; set; }

        /// <summary>
        /// returns a default user mapping example
        /// </summary>
        /// <returns>example mapping</returns>
        public static TfsImpersonationMap[] GetMappings()
        {
            var mappings = new TfsImpersonationMap[2];
            mappings[0] = new TfsImpersonationMap {SourceUserName = "*\\zjdau", TargetUserName = "zjdau", TargetPassword = "pwd"};
            mappings[1] = new TfsImpersonationMap {SourceUserName = "Sebastian Dau", TargetUserName = "zjdau", TargetPassword = "pwd"};
            return mappings;
        }

        /// <summary>
        /// reads a custom mapping setup from an xml file through de-serialization)
        /// </summary>
        /// <param name="path">path of the file</param>
        /// <returns></returns>
        public static TfsImpersonationMap[] GetMappings(string path)
        {
            if (!File.Exists(path))
                throw new FileNotFoundException("UserMapping.xml not found. Configure appropriate path in Web Project Settings!", path);

            using (var xr = new XmlTextReader(path))
            {
                var xs = new XmlSerializer(typeof (TfsImpersonationMap[]));
                return (TfsImpersonationMap[]) xs.Deserialize(xr);
            }
        }

        /// <summary>
        /// Saves the mappings into a file
        /// </summary>
        /// <param name="mappings"></param>
        /// <param name="path"></param>
        public static void SetMappings(TfsImpersonationMap[] mappings, string path)
        {
            using (XmlTextWriter xt = new XmlTextWriter(path, Encoding.UTF8))
            {
                XmlSerializer xs = new XmlSerializer(mappings.GetType());
                xt.Formatting = Formatting.Indented;
                xs.Serialize(xt, mappings);
            }
        }
    }
}